from django import forms
from django.forms import fields
from django.forms import widgets

from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator

from userInfo.models import User

#登录组件
class UserForm(forms.Form):
    uname = fields.CharField(max_length=20,min_length=1,label='用户名',required=True)
    upwd = fields.CharField(max_length=20,min_length=1,label='密码',required=True,widget=widgets.PasswordInput)

#注册组件
class RegisterForm(forms.Form):
    uname = fields.CharField(max_length=20, min_length=1, label='用户名', required=True,widget=widgets.TextInput(attrs={'class':'form-control'}))
    upwd = fields.CharField(max_length=20, min_length=1, label='密码', required=True,widget=widgets.PasswordInput(attrs={'class':'form-control','id':'exampleInputPassword1'}))
    ulev = fields.ChoiceField(
        choices=((0,'超级用户'),(1,'普通用户'),(2,'待审核用户')),
        initial=2,
        # widget=widgets.RadioSelect,
        label='类别',
        widget = widgets.Select(attrs={'readonly':True,'class':'form-control'}),

    )
    utel = fields.CharField(max_length=11,min_length=11,label='电话',widget=widgets.NumberInput(attrs={'class':'form-control'}))
    uaddr = fields.CharField(max_length=32,label='地址',widget=widgets.TextInput(attrs={'class':'form-control'}))
    uimg = fields.ImageField(label='图片',widget=widgets.FileInput(attrs={'id':'exampleInputFile'}))

    #图片验证
    def clean_uimg(self):
        value = self.cleaned_data['uimg']
        if value.name.split('.')[-1] not in ['jpg','png']:
            raise ValidationError('只能录入jpg,png格式的图片')
        else:
            return value

    #用户验证
    def clean_uname(self):
        value = self.cleaned_data['uname']
        print('---',value)
        if User.objects.filter(uname=value):
            raise  ValidationError('该用户已经存在')
        else:
            return value
